<?php

namespace App\Jobs;

use App\Models\TourOrder;
use App\Services\CommissionService;
use App\Services\UserAccountService;
use Illuminate\Support\Facades\DB;

class TourOrderConfirmJob extends Job
{
    protected $job_name ='TourOrderConfirmJob';
    private $runtime = null;
    private $rows_per_loop =10;

    /**
     * 创建一个新的任务实例。
     *
     * @param $time 启动时间
     */
    public function __construct($time)
    {
        parent::__construct();
        $this->runtime = $time;
    }

    /**
     * 运行任务。
     *
     * @return void
     */
    public function handle()
    {
        //业务说明：到达出行日期出行成功

        $this->logger->info('========start======');
        $this->logger->info('runtime:'.$this->runtime);
        $timeline = $this->runtime;

        //单买线路订单自动确认
        $this->confirmTourOrder($timeline);
        //团购订单自动确认
        $this->confirmTourOrderGroup($timeline);

        $this->logger->info('========end======');
    }

    private function confirmTourOrder($timeline){

        //
        $commission = new CommissionService();
        $user_account = new UserAccountService();

        $this->logger->info('========线路订单单买======');

        $i =1;//批次
        $orders =null;

        while(true){

            $this->logger->info('【第'.$i.'批】');

            /* 到达出行日期的线路订单 */
            $tour_orders = DB::table('tour_order')
                    ->leftJoin('tour_order_tour', 'tour_order.order_id', '=', 'tour_order_tour.order_id')
                    ->where('tour_order_tour.open_date','<=',$timeline+24*3600)
                    ->where('tour_order.status','=',TOUR_ORDER_ACCEPTED)
                    ->where('tour_order.extension','=','normal')
                    ->skip(0)->take($this->rows_per_loop)
                    ->lists('tour_order.order_id');

            $this->logger->info('总数:'.count($tour_orders));

            if(count($tour_orders)==0){
                break;
            }

            $this->logger->info('执行: '.json_encode($tour_orders));
            /* 操作日志 */
            $order_shipped = '待出行';
            $order_finished= '已完成';

            DB::beginTransaction();

            try{

                /* 更新订单状态 */
                DB::table('tour_order')
                    ->whereIn('order_id',$tour_orders)
                    ->update([
                        'status' => TOUR_ORDER_FINISHED,
                        'finished_time' => $this->runtime
                    ]);

                /* 操作记录 */
                foreach ($tour_orders as $order_id )
                {
                    $order_logs[] = array(
                        'order_id'  => $order_id,
                        'operator'  => '0',
                        'order_status' => $order_shipped,
                        'changed_status' => $order_finished,
                        'remark'    => '',
                        'log_time'  => $timeline,
                    );
                }

                foreach($order_logs as $orderlog){
                    DB::table('tour_order_log')->insert($orderlog);
                }

                //确认出行之后 计算收益
                $order_info =TourOrder::whereIn('order_id',$tour_orders)
                    ->select('seller_id','order_amount','buyer_id','order_id','order_sn')
                    ->get();

                foreach($order_info as $value){
                    //用户确认收货收益计算
                    $account_money = $commission->getCommission($value['seller_id'],$value['order_amount'],'tour');
                    //平台收益
                    $admin_commission = $account_money['franchisee_commission_goods']; //平台收益比例
                    $admin_money = 	$account_money['admin_money'];

                    //加盟商收益
                    $franchisee_commission = $account_money['partner_commission']; //加盟商收益比例
                    $franchisee_money = $account_money['franchisee_money'];

                    //合伙人收益
                    $partner_money = $account_money['partner_money'];

                    //账户资金操作  以及记录日志
                    if($admin_money > 0 ){
                        $user_account->incomeMoney(1,$admin_money,'结算线路订单:订单编号:'.$value['order_sn'].'分成比例:'.$admin_commission.'%',$value['order_id'],'tour','+');
                    }

                    if($franchisee_money > 0 && $account_money['franchisee_id'] > 0){
                        $user_account->incomeMoney($account_money['franchisee_id'],$franchisee_money,'结算线路订单:订单编号:'.$value['order_sn'].'分成比例:'.$franchisee_commission.'%',$value['order_id'],'tour','+');
                    }

                    if($partner_money > 0){
                        $user_account->incomeMoney($value['seller_id'],$partner_money,'结算线路订单:订单编号:'.$value['order_sn'],$value['order_id'],'tour','+');
                    }
                }

                DB::commit();

            } catch(\Exception $e){
                DB::rollback();
                $this->logger->info('error msg:'. $e->getMessage() . ' trace:'. $e->getTraceAsString());
                //throw $e;
            }

            if(count($tour_orders)<$this->rows_per_loop){
                break;
            }

            $i++;

        }

    }

    private function confirmTourOrderGroup($timeline){

        $commission = new CommissionService();
        $user_account = new UserAccountService();
        //
        $this->logger->info('========团购线路订单======');

        $i =1;//批次
        $orders =null;

        while(true){

            $this->logger->info('【第'.$i.'批】');

            /* 到达出行日期的线路订单 */
            $tour_orders = DB::table('tour_order')
                ->leftJoin('tour_order_tour', 'tour_order.order_id', '=', 'tour_order_tour.order_id')
                ->leftJoin('tour_tuan', function ($join) {
                    $join->on('tour_tuan.tuan_id', '=', 'tour_order.tuan_id')
                        ->where('tour_tuan.state','=', TUAN_DATA_STATE_SUCCESS);
                })
                ->where('tour_order_tour.open_date','<=',$timeline+24*3600)
                ->where('tour_order.status','=',TOUR_ORDER_ACCEPTED)
                ->where('tour_order.extension','=','groupbuy')
                ->skip(0)->take($this->rows_per_loop)
                ->lists('tour_order.order_id');

            $this->logger->info('总数:'.count($tour_orders));

            if(count($tour_orders)==0){
                break;
            }
            $this->logger->info('执行: '.json_encode($tour_orders));

            $order_shipped = '待出行';
            $order_finished= '已完成';

            DB::beginTransaction();
            try{

                /* 更新订单状态 */
                DB::table('tour_order')
                    ->whereIn('order_id',$tour_orders)
                    ->update([
                        'status' => TOUR_ORDER_FINISHED,
                        'finished_time' => $timeline
                    ]);

                /* 操作记录 */
                foreach ($tour_orders as $order_id )
                {
                    $order_logs[] = array(
                        'order_id'  => $order_id,
                        'operator'  => '0',
                        'order_status' => $order_shipped,
                        'changed_status' => $order_finished,
                        'remark'    => '',
                        'log_time'  => $timeline,
                    );
                }

                foreach($order_logs as $orderlog){
                    DB::table('tour_order_log')->insert($orderlog);
                }

                //确认出行之后 计算收益
                $order_info =TourOrder::whereIn('order_id',$tour_orders)
                    ->select('seller_id','order_amount','buyer_id','order_id','order_sn')
                    ->get();

                foreach($order_info as $value){
                    //用户确认收货收益计算
                    $account_money = $commission->getCommission($value['seller_id'],$value['order_amount'],'tour');
                    //平台收益
                    $admin_commission = $account_money['data']['franchisee_commission_goods']; //平台收益比例
                    $admin_money = 	$account_money['data']['admin_money'];

                    //加盟商收益
                    $franchisee_commission = $account_money['data']['partner_commission']; //加盟商收益比例
                    $franchisee_money = $account_money['data']['franchisee_money'];

                    //合伙人收益
                    $partner_money = $account_money['data']['partner_money'];

                    //账户资金操作  以及记录日志
                    if($admin_money > 0 ){
                        $user_account->incomeMoney(1,$admin_money,'结算线路订单:订单编号:'.$value['order_sn'].'分成比例:'.$admin_commission.'%',$value['order_id'],'tour','+');
                    }

                    if($franchisee_money > 0 && $account_money['data']['franchisee_id'] > 0){
                        $user_account->incomeMoney($account_money['data']['franchisee_id'],$franchisee_money,'结算线路订单:订单编号:'.$value['order_sn'].'分成比例:'.$franchisee_commission.'%',$value['order_id'],'tour','+');
                    }

                    if($partner_money > 0){
                        $user_account->incomeMoney($value['seller_id'],$partner_money,'结算线路订单:订单编号:'.$value['order_sn'].'',$value['order_id'],'tour','+');
                    }
                }

                DB::commit();

            } catch(\Exception $e){
                DB::rollback();
                $this->logger->info('error msg:'. $e->getMessage() . ' trace:'. $e->getTraceAsString());
                //throw $e;
            }

            if(count($tour_orders)<$this->rows_per_loop){
                break;
            }

            $i++;

        }

    }

}
